﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.Collections.Generic;
using System.Transactions;
using ZenSystemService.Api.Business;
using ZenSystemService.Api.Common;
using ZenSystemService.Api.Common.Auth;
using ZenSystemService.Api.DTOs;
using ZenSystemService.Api.Entities;
using ZenSystemService.Api.Services;

namespace ZenSystemService.Api.Controllers
{
    [Route("api/traineeorder")]
    [ApiController]
    public class TraineeOrderController: ControllerBase
    {
        private readonly UserService _userService;
        private readonly UserBusiness _userBusiness;
        private readonly TraineeOrderService _traineeOrderService;
        private readonly CourseService _courseService;
        private readonly DTOBusiness _dTOBusiness;
        private readonly RecommendTermService _recommendTermService;
        public TraineeOrderController(UserService userService, UserBusiness userBusiness
            , TraineeOrderService traineeOrderService, CourseService courseService, DTOBusiness dTOBusiness, RecommendTermService recommendTermService)
        {
            _userService = userService;
            _userBusiness = userBusiness;
            _traineeOrderService = traineeOrderService;
            _courseService = courseService;
            _dTOBusiness = dTOBusiness;
            _recommendTermService = recommendTermService;
        }

        /// <summary>
        /// 创建学员订单
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("CreateTraineeOrder")]
        public async Task<ReturnObjectT<CreateTraineeOrderResponse>> CreateTraineeOrder(ReceiveObjectT<CreateTraineeOrderDTO> _receiveObjectT)
        {
            ReturnObjectT<CreateTraineeOrderResponse> _returnObject = new ReturnObjectT<CreateTraineeOrderResponse>();

            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;

            /*
            //判断手机号是否存在 不存在则创建用户
            User _user = await _userService.GetTraineeByPhoneAsync(_receiveObjectT.Data.Mobile);
            User newUser;
            if (_user == null)
            {
                if (!_userBusiness.CreateInitialTrainee(_receiveObjectT.Data.Mobile, out newUser))
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "操作(创建用户失败)";
                    return _returnObject;
                }
            }
            else
            {
                newUser = _user;
            }*/
            CreateTraineeOrderResponse createTraineeOrderResponse=new CreateTraineeOrderResponse ();
            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                //创建订单/订单明细
                TraineeOrder traineeOrder=new TraineeOrder();
                traineeOrder.InstitutionId= _receiveObjectT.Data.InstitutionId;
                traineeOrder.TraineeId = _receiveObjectT.Data.TraineeId;
                traineeOrder.BuyCourseTotalPrice = _receiveObjectT.Data.TotalPrice;
                traineeOrder.SalesUserId = _receiveObjectT.Data.SalesUserId;
                traineeOrder.SaveImage = _receiveObjectT.Data.SaveImage;
                traineeOrder.BuyDate = DateTime.Now;
                traineeOrder.CreatedUserID = userid;
                traineeOrder.CreatedDate= DateTime.Now;
                traineeOrder.PaymentStatus = 0;//付款状态 0=未付款
                if (!_traineeOrderService.CreateTraineeOrder(ref traineeOrder))
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "创建订单失败";
                    return _returnObject;
                }
                createTraineeOrderResponse.TraineeOrderId = traineeOrder.TraineeOrderId;
                IList<CreateTraineeOrderDetailDTO> CreateTraineeOrderDetailList = _receiveObjectT.Data.TraineeOrderDetailList;
                if(CreateTraineeOrderDetailList==null|| CreateTraineeOrderDetailList.Count==0)
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "数据错误";
                    return _returnObject;
                }
                for (int i = 0; i < CreateTraineeOrderDetailList.Count; i++)
                {
                    CourseType _courseType = await _courseService.GetCourseTypeByIdAsync(CreateTraineeOrderDetailList[i].BuyCourseTypeId);
                    TraineeOrderDetail traineeOrderDetail = new TraineeOrderDetail();
                    traineeOrderDetail.TraineeOrderId = traineeOrder.TraineeOrderId;
                    traineeOrderDetail.TraineeId = CreateTraineeOrderDetailList[i].TraineeId;
                    traineeOrderDetail.BuyCourseTypeId = CreateTraineeOrderDetailList[i].BuyCourseTypeId;
                    traineeOrderDetail.CoachId = CreateTraineeOrderDetailList[i].CoachId;
                    traineeOrderDetail.BuyCourseNum = CreateTraineeOrderDetailList[i].BuyCourseNum;
                    traineeOrderDetail.BuyCoursePrice = CreateTraineeOrderDetailList[i].BuyCourseNum*_courseType.Price;
                    if (!_traineeOrderService.CreateTraineeOrderDetail(ref traineeOrderDetail))
                    {
                        _returnObject.Code = 0;
                        _returnObject.ErrorMsg = "创建订单失败";
                        return _returnObject;
                    }


                    IList<TraineeOrderRecommendTermDetailDTO> TraineeOrderRecommendTermDetailDTOList = CreateTraineeOrderDetailList[i].TraineeOrderRecommendTermDetailDTOList;
                    if (TraineeOrderRecommendTermDetailDTOList != null && TraineeOrderRecommendTermDetailDTOList.Count > 0)
                    {
                        for (int j = 0; j < TraineeOrderRecommendTermDetailDTOList.Count; j++)
                        {
                            TraineeOrderRecommendTermDetail _traineeOrderRecommendTermDetail = new TraineeOrderRecommendTermDetail();
                            _traineeOrderRecommendTermDetail.TraineeOrderDetailId = traineeOrderDetail.TraineeOrderDetailId;
                            _traineeOrderRecommendTermDetail.RecommendTermId = TraineeOrderRecommendTermDetailDTOList[j].RecommendTermId;
                            _traineeOrderRecommendTermDetail.Num = TraineeOrderRecommendTermDetailDTOList[j].Num;
                            bool saveTermDetailIsSuccess = await _traineeOrderService.AddTraineeOrderRecommendTermDetail(_traineeOrderRecommendTermDetail);
                            if (!saveTermDetailIsSuccess)
                            {
                                _returnObject.Code = 0;
                                _returnObject.ErrorMsg = "创建订单失败";
                                return _returnObject;
                            }
                        }
                    }

                }
                transScope.Complete();
            }
            _returnObject.Code = 1;
            _returnObject.Data = createTraineeOrderResponse;
            return _returnObject;
        }


        /// <summary>
        /// 学员订单支付
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("TraineeOrderPayment")]
        public async Task<ReturnObject> TraineeOrderPayment(ReceiveObjectT<TraineeOrderPaymentRequest> _receiveObjectT)
        {
            ReturnObject _returnObject = new ReturnObject();

            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;
            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                //订单ID
                int TraineeOrderId = _receiveObjectT.Data.TraineeOrderId;
                TraineeOrder _traineeOrder = await _traineeOrderService.GetTraineeOrderInfo(TraineeOrderId);
                _traineeOrder.PaymentStatus = 1;
                _traineeOrder.PaymentOperUserId = userid;
                _traineeOrder.PaymentTime = DateTime.Now;
                bool updateIsSuccess = await _traineeOrderService.UpdateTraineeOrderAsync(_traineeOrder);
                if (!updateIsSuccess)
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "操作失败";
                    return _returnObject;
                }

                //获取订单明细
                List<TraineeOrderDetail> TraineeOrderDetailList = await _traineeOrderService.GetTraineeOrderDetailList(TraineeOrderId);
                if (TraineeOrderDetailList != null && TraineeOrderDetailList.Count > 0)
                {
                    for (int i = 0; i < TraineeOrderDetailList.Count; i++)
                    {
                        //设置学员剩余数
                        TraineeCourseSurplus _traineeCourseSurplus = await _traineeOrderService.GetTraineeCourseSurplus(TraineeOrderDetailList[i].BuyCourseTypeId, TraineeOrderDetailList[i].TraineeId, TraineeOrderDetailList[i].CoachId);
                        if (_traineeCourseSurplus == null)
                        {
                            TraineeCourseSurplus newTraineeCourseSurplus = new TraineeCourseSurplus();
                            newTraineeCourseSurplus.CourseTypeId = TraineeOrderDetailList[i].BuyCourseTypeId;
                            newTraineeCourseSurplus.TraineeId = TraineeOrderDetailList[i].TraineeId;
                            newTraineeCourseSurplus.SurplusCourseNum = TraineeOrderDetailList[i].BuyCourseNum;
                            newTraineeCourseSurplus.CoachId = TraineeOrderDetailList[i].CoachId;
                            if (!_traineeOrderService.AddTraineeCourseSurplusAsync(ref newTraineeCourseSurplus))
                            {
                                _returnObject.Code = 0;
                                _returnObject.ErrorMsg = "操作失败";
                                return _returnObject;
                            }
                        }
                        else
                        {
                            _traineeCourseSurplus.SurplusCourseNum = _traineeCourseSurplus.SurplusCourseNum + TraineeOrderDetailList[i].BuyCourseNum;
                            bool updateSurpluIsSuccess = await _traineeOrderService.UpdateTraineeCourseSurplusAsync(_traineeCourseSurplus);
                            if (!updateSurpluIsSuccess)
                            {
                                _returnObject.Code = 0;
                                _returnObject.ErrorMsg = "操作失败";
                                return _returnObject;
                            }
                        }
                    }
                }
                transScope.Complete();
            }
            _returnObject.Code = 1;
            return _returnObject;
        }

        /// <summary>
        /// 获取学员订单列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetTraineeOrderList")]
        public async Task<ReturnObjectT<List<TraineeOrder>>> GetTraineeOrderList(ReceiveObjectT<TraineeOrderQuery> _receiveObjectT)
        {
            ReturnObjectT<List<TraineeOrder>> _returnObject = new ReturnObjectT<List<TraineeOrder>>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;
            int recordCount;
            IEnumerable<TraineeOrder> list = _traineeOrderService.GetTraineeOrderList(_receiveObjectT.Page, _receiveObjectT.PageSize, _receiveObjectT.Data.InstitutionId, _receiveObjectT.Data.PaymentStatus, out recordCount);
            List<TraineeOrder> TraineeOrderList = null;
            if (list != null)
                TraineeOrderList = list.ToList();
            if (TraineeOrderList != null && TraineeOrderList.Count > 0)
            {
                IEnumerable<User> userlist = await _userService.GetAllUsersAsync();
                List<User> AllUserList = userlist.ToList();
                for (int i = 0; i < TraineeOrderList.Count; i++)
                {
                    _dTOBusiness.JointSearchTraineeOrder(TraineeOrderList[i], AllUserList);
                }
            }
            _returnObject.Code = 1;
            _returnObject.Data = TraineeOrderList;
            _returnObject.RecordTotalCount = recordCount;
            return _returnObject;
        }

        /// <summary>
        /// 获取学员自己的学员订单列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetTraineeOwnTraineeOrderList")]
        public async Task<ReturnObjectT<List<TraineeOrder>>> GetTraineeOwnTraineeOrderList()
        {
            ReturnObjectT<List<TraineeOrder>> _returnObject = new ReturnObjectT<List<TraineeOrder>>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;
            IEnumerable<TraineeOrder> list = _traineeOrderService.GetTraineeOrderList(userid);
            List<TraineeOrder> TraineeOrderList = null;
            if (list != null)
                TraineeOrderList = list.ToList();
            if (TraineeOrderList != null && TraineeOrderList.Count > 0)
            {
                IEnumerable<User> userlist = await _userService.GetAllUsersAsync();
                List<User> AllUserList = userlist.ToList();
                for (int i = 0; i < TraineeOrderList.Count; i++)
                {
                    _dTOBusiness.JointSearchTraineeOrder(TraineeOrderList[i], AllUserList);
                }
            }
            _returnObject.Code = 1;
            _returnObject.Data = TraineeOrderList;
            return _returnObject;
        }


        /// <summary>
        /// 获取学员订单详情信息
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("GetTraineeOrderInfoById")]
        public async Task<ReturnObjectT<TraineeOrder>> GetTraineeOrderInfoById(ReceiveObjectT<TraineeOrderPaymentRequest> _receiveObjectT)
        {
            ReturnObjectT<TraineeOrder> _returnObject=new ReturnObjectT<TraineeOrder>();
            
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户未登录";
                return _returnObject;
            }
            int userid = userModel.UserId;
            
            IEnumerable<User> userlist = await _userService.GetAllUsersAsync();
            List<User> AllUserList = null;
            if (userlist != null)
                AllUserList = userlist.ToList();

            TraineeOrder traineeOrder = await _traineeOrderService.GetTraineeOrderInfo(_receiveObjectT.Data.TraineeOrderId);
            _dTOBusiness.JointSearchTraineeOrder(traineeOrder, AllUserList);

            IEnumerable<CourseType> courseTypeList = await _courseService.GetCourseTypeListAsync(traineeOrder.InstitutionId);
            List<CourseType> CourseTypeList = null;
            if (courseTypeList != null)
                CourseTypeList= courseTypeList.ToList();

            IEnumerable<RecommendTerm> rtlist = await _recommendTermService.GetRecommendTermListAsync(traineeOrder.InstitutionId);
            List<RecommendTerm> RecommendTermList = null;
            if (rtlist != null)
                RecommendTermList = rtlist.ToList();

            traineeOrder.TraineeOrderDetailList = await _traineeOrderService.GetTraineeOrderDetailList(_receiveObjectT.Data.TraineeOrderId);
            if (traineeOrder.TraineeOrderDetailList != null && traineeOrder.TraineeOrderDetailList.Count > 0)
            {
                for (int i = 0; i < traineeOrder.TraineeOrderDetailList.Count; i++)
                {
                    _dTOBusiness.JointSearchTraineeOrderDetail(traineeOrder.TraineeOrderDetailList[i], AllUserList, CourseTypeList);

                    traineeOrder.TraineeOrderDetailList[i].TraineeOrderRecommendTermDetailList =await  _traineeOrderService.GetTraineeOrderRecommendTermDetailList(traineeOrder.TraineeOrderDetailList[i].TraineeOrderDetailId);

                    if (traineeOrder.TraineeOrderDetailList[i].TraineeOrderRecommendTermDetailList != null)
                    {
                        for (int j = 0; j < traineeOrder.TraineeOrderDetailList[i].TraineeOrderRecommendTermDetailList.Count; j++)
                        {
                            if (RecommendTermList != null)
                            {
                                RecommendTerm _recommendTerm = RecommendTermList.FirstOrDefault(item => item.RecommendTermId == traineeOrder.TraineeOrderDetailList[i].TraineeOrderRecommendTermDetailList[j].RecommendTermId);
                                if (_recommendTerm != null)
                                    traineeOrder.TraineeOrderDetailList[i].TraineeOrderRecommendTermDetailList[j].RecommendTermName = _recommendTerm.Name;
                            }
                        }
                    }
                }
            }
            traineeOrder.PaymentStatusTxt = traineeOrder.PaymentStatus == 0 ? "未付款" : "已付款";
            _returnObject.Code = 1;
            _returnObject.Data = traineeOrder;
            return _returnObject;
        }
    }
}
